package com.sq.util.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sq.util.StringUtil;

public class NetUtil {

    private static final Logger log = LoggerFactory.getLogger(NetUtil.class);

    public static void checkPort(int port) {
        try {
            Socket socket = new Socket();
            socket.bind(new InetSocketAddress(port));
            socket.close();
        } catch (IOException e) {
            System.err.println("端口[" + port + "]被占用");
            e.printStackTrace();
            System.exit(0);
        }
    }

    public static String encode(String str) {
        return encode(str, StandardCharsets.UTF_8.name());
    }

    public static String encode(String str, String enc) {
        if (StringUtil.isBlank(str)) {
            return "";
        }
        try {
            return URLEncoder.encode(str, enc);
        } catch (UnsupportedEncodingException e) {
            log.error("编码[" + str + "]出错" + e.getMessage(), e);
            return str;
        }
    }

    public static String decode(String str) {
        return decode(str, StandardCharsets.UTF_8.name());
    }

    public static String decode(String str, String enc) {
        if (StringUtil.isBlank(str)) {
            return "";
        }
        try {
            return URLDecoder.decode(str, enc);
        } catch (UnsupportedEncodingException e) {
            log.error("解码[" + str + "]出错" + e.getMessage(), e);
            return str;
        }
    }

    public static String toFormFormat(Map<String, String> params) {
        StringBuilder paramSb = new StringBuilder(128);
        boolean flag = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (flag) {
                flag = false;
            } else {
                paramSb.append('&');
            }
            paramSb.append(NetUtil.encode(entry.getKey()));
            paramSb.append('=').append(NetUtil.encode(entry.getValue()));
        }
        return paramSb.toString();
    }
}
